package queue

import (
    "fmt"
    "github.com/streadway/amqp"
    "log"
)

var Connection *amqp.Connection
var Channel *amqp.Channel

func InitRabbitMQ() {
    var err error
    Connection, err = amqp.Dial("amqp://guest:guest@localhost:5672/")
    if err != nil {
        log.Fatalf("Failed to connect to RabbitMQ: %v", err)
    }

    Channel, err = Connection.Channel()
    if err != nil {
        log.Fatalf("Failed to open channel: %v", err)
    }

    log.Println("RabbitMQ initialized")
}

func PublishMessage(queueName, message string) error {
    q, err := Channel.QueueDeclare(
        queueName, // name
        false,     // durable
        false,     // delete when unused
        false,     // exclusive
        false,     // no-wait
        nil,       // arguments
    )
    if err != nil {
        return fmt.Errorf("failed to declare queue: %w", err)
    }

    err = Channel.Publish(
        "",     // exchange
        q.Name, // routing key
        false,  // mandatory
        false,  // immediate
        amqp.Publishing{
            ContentType: "text/plain",
            Body:        []byte(message),
        })
    if err != nil {
        return fmt.Errorf("failed to publish message: %w", err)
    }

    log.Println("Message published successfully")
    return nil
}